package com.ruoyi.web.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.web.domain.AppUser;
import com.ruoyi.web.domain.RechargeRecord;
import com.ruoyi.web.dto.RechargeRecordDTO;
import com.ruoyi.web.enums.RechargeRecordEnum;
import com.ruoyi.web.mapper.RechargeRecordMapper;
import com.ruoyi.web.service.IAppUserService;
import com.ruoyi.web.service.IRechargeRecordService;
import com.ruoyi.web.vo.UserRechargeRecordVO;
import com.ruoyi.web.vo.UserRewardRecordVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 充值记录Controller
 *
 * @author ruoyi
 * @date 2022-12-30
 */
@RestController
@RequestMapping("/record")
@AllArgsConstructor
public class RechargeRecordController extends BaseController {
    private final IRechargeRecordService rechargeRecordService;
    private final RechargeRecordMapper rechargeRecordMapper;
    private final IAppUserService appUserService;

    /**
     * app 充值记录
     *
     * @return
     */
    @GetMapping
    public TableDataInfo getUserRecord() {
        try {
            List<RechargeRecord> list = rechargeRecordService.getUserRecord();
            TableDataInfo info = getDataTable(list);

            List<UserRechargeRecordVO> voList = new ArrayList<>();
            for (RechargeRecord i : list) {
                UserRechargeRecordVO vo = new UserRechargeRecordVO();
                BeanUtils.copyProperties(i, vo);
                vo.setState(RechargeRecordEnum.Status.findName(vo.getState()));
                vo.setType(RechargeRecordEnum.Type.findName(vo.getType()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(i.getCreateTime());
                vo.setCreateTime(format);
                voList.add(vo);
            }

            return getDataTable(info, voList);

        } catch (TadpoleException exception) {
            throw exception;
        } catch (Exception e) {
            throw new TadpoleException(AbnormalEnum.MSG.DISCONNECTED);
        }
    }

    /**
     * app 奖励记录
     *
     * @return
     */
    @GetMapping("/reward")
    public TableDataInfo rewardList() {
        try {
            List<RechargeRecord> list = rechargeRecordService.getUserRewardRecord();
            TableDataInfo info = getDataTable(list);

            List<UserRewardRecordVO> voList = new ArrayList<>();
            for (RechargeRecord i : list) {
                UserRewardRecordVO vo = new UserRewardRecordVO();
                BeanUtils.copyProperties(i, vo);
                vo.setState(RechargeRecordEnum.Status.findName(vo.getState()));
                vo.setType(RechargeRecordEnum.Type.findName(vo.getType()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(i.getCreateTime());
                vo.setCreateTime(format);
                voList.add(vo);
            }

            return getDataTable(info, voList);

        } catch (TadpoleException exception) {
            throw exception;
        } catch (Exception e) {
            throw new TadpoleException(AbnormalEnum.MSG.DISCONNECTED);
        }
    }

//    /**
//     * app 奖励记录
//     * @return
//     */
//    @GetMapping("/profit")
//    public TableDataInfo profitList()
//    {
//        return getDataTable(rechargeRecordService.getUserRewardRecord());
//    }

    /**
     * 查询充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('web:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(RechargeRecord rechargeRecord) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser.getUser().getRoles().get(0).getRoleId() == 3) {
            // 获取所有子集
            List<AppUser> userList = new ArrayList<>();
            appUserService.getAllChild(userList, loginUser.getUserId());
            List<Long> userIdList = userList.stream()
                    .map(AppUser::getId)
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIdList)) {
                return getDataTable(new ArrayList<>());
            }

            List<String> typeList = new ArrayList<>(2);
            typeList.add("1");
            typeList.add("2");

            RechargeRecordDTO condition = new RechargeRecordDTO();
            condition.setUserIdList(userIdList);
            condition.setTypeList(typeList);
            condition.setUserId(rechargeRecord.getUserId());

            return selectAgentList(condition);
        } else {
            startPage();
            List<RechargeRecord> records = rechargeRecordService.selectRechargeRecordList(rechargeRecord);
            TableDataInfo info = getDataTable(records);

            List<UserRechargeRecordVO> list = new ArrayList<>();
            for (RechargeRecord record : records) {
                UserRechargeRecordVO vo = new UserRechargeRecordVO();
                BeanUtils.copyProperties(record, vo);
                vo.setState(RechargeRecordEnum.Status.findName(vo.getState()));
                vo.setType(RechargeRecordEnum.Type.findName(vo.getType()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(record.getCreateTime());
                vo.setCreateTime(format);
                list.add(vo);
            }
            return getDataTable(info, list);
        }
    }

    /**
     * 查询奖励记录列表
     */
    @PreAuthorize("@ss.hasPermi('web:record:list')")
    @GetMapping("/reward/list")
    public TableDataInfo rewardList(RechargeRecord rechargeRecord) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser.getUser().getRoles().get(0).getRoleId() == 3) {
            // 获取所有子集
            List<AppUser> userList = new ArrayList<>();
            appUserService.getAllChild(userList, loginUser.getUserId());
            List<Long> userIdList = userList.stream()
                    .map(AppUser::getId)
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIdList)) {
                return getDataTable(new ArrayList<>());
            }

            List<String> typeList = new ArrayList<>(3);
            typeList.add("3");
            typeList.add("4");
            typeList.add("7");

            RechargeRecordDTO condition = new RechargeRecordDTO();
            condition.setUserIdList(userIdList);
            condition.setTypeList(typeList);
            condition.setUserId(rechargeRecord.getUserId());

            return selectAgentList(condition);

        } else {
            startPage();
            List<RechargeRecord> records = rechargeRecordMapper.selectRewardRecordList(rechargeRecord);
            TableDataInfo info = getDataTable(records);

            List<UserRechargeRecordVO> list = new ArrayList<>();
            for (RechargeRecord record : records) {
                UserRechargeRecordVO vo = new UserRechargeRecordVO();
                BeanUtils.copyProperties(record, vo);
                vo.setState(RechargeRecordEnum.Status.findName(vo.getState()));
                vo.setType(RechargeRecordEnum.Type.findName(vo.getType()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(record.getCreateTime());
                vo.setCreateTime(format);
                list.add(vo);
            }
            return getDataTable(info, list);
        }
    }

    /**
     * 代理查询充值记录
     *
     * @param condition 查询条件
     * @return {@link TableDataInfo}
     * @since 2023/4/4 13:07
     */
    public TableDataInfo selectAgentList(RechargeRecordDTO condition) {
        startPage();
        List<RechargeRecord> records = rechargeRecordMapper.selectChildRechargeRecordList(condition);
        TableDataInfo info = getDataTable(records);

        List<UserRechargeRecordVO> list = new ArrayList<>();
        for (RechargeRecord record : records) {
            UserRechargeRecordVO vo = new UserRechargeRecordVO();
            BeanUtils.copyProperties(record, vo);
            vo.setState(RechargeRecordEnum.Status.findName(vo.getState()));
            vo.setType(RechargeRecordEnum.Type.findName(vo.getType()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(record.getCreateTime());
            vo.setCreateTime(format);
            list.add(vo);
        }
        return getDataTable(info, list);
    }


    /**
     * 导出充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('web:record:export')")
    @Log(title = "充值记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RechargeRecord rechargeRecord) {
        List<RechargeRecord> list = rechargeRecordService.selectRechargeRecordList(rechargeRecord);
        ExcelUtil<RechargeRecord> util = new ExcelUtil<RechargeRecord>(RechargeRecord.class);
        util.exportExcel(response, list, "充值记录数据");
    }

    /**
     * 获取充值记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('web:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(rechargeRecordService.selectRechargeRecordById(id));
    }

    /**
     * 新增充值记录
     */
    @PreAuthorize("@ss.hasPermi('web:record:add')")
    @Log(title = "充值记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RechargeRecord rechargeRecord) {
        return toAjax(rechargeRecordService.insertRechargeRecord(rechargeRecord));
    }

    /**
     * 修改充值记录
     */
    @PreAuthorize("@ss.hasPermi('web:record:edit')")
    @Log(title = "充值记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RechargeRecord rechargeRecord) {
        return toAjax(rechargeRecordService.updateRechargeRecord(rechargeRecord));
    }

    /**
     * 删除充值记录
     */
    @PreAuthorize("@ss.hasPermi('web:record:remove')")
    @Log(title = "充值记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(rechargeRecordService.deleteRechargeRecordByIds(ids));
    }
}
